#!/bin/bash

# Configuration
# Only set TARGET_ORG if not already defined
: "${TARGET_ORG:=Cangjie}"

# Check if at least four arguments are provided (title, branch, target_branch, and at least one repo)
if [[ $# -lt 4 ]]; then
    echo "Error: Title, branch name, target branch, and at least one repository are required"
    echo "Usage: $0 \"commit title\" \"branch_name\" \"target_branch\" repo1 [repo2] ..."
    exit 1
fi

TITLE="$1"
BRANCH_NAME="$2"
TARGET_BRANCH="$3"

# Get all remaining arguments as repo names
shift 3
REPO_NAMES=("$@")

# Check if REPO_NAMES is not empty
if [[ ${#REPO_NAMES[@]} -eq 0 ]]; then
    echo "Error: At least one repository must be specified"
    exit 1
fi

# Use the first repo for issue creation
ISSUE_REPO="${REPO_NAMES[0]}"

CONFIG_FILE="$HOME/.config/cjpr.conf"

# Check if config file exists
if [[ ! -f "$CONFIG_FILE" ]]; then
    echo "Error: Config file not found at $CONFIG_FILE"
    echo ""
    echo "Please create the config file with the following format:"
    echo "GITCODE_USER=username"
    echo "TOKEN=token-id"
    exit 1
fi

# Initialize variables
GITCODE_USER=""
TOKEN=""

# Read the config file line by line
while IFS= read -r line; do
    # Skip empty lines and comments
    [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
    
    # Parse GITCODE_USER
    if [[ "$line" =~ ^GITCODE_USER= ]]; then
        GITCODE_USER="${line#GITCODE_USER=}"
    fi
    
    # Parse TOKEN
    if [[ "$line" =~ ^TOKEN= ]]; then
        TOKEN="${line#TOKEN=}"
    fi
done < "$CONFIG_FILE"

# Check if both variables are set and non-empty
if [[ -z "$GITCODE_USER" || -z "$TOKEN" ]]; then
    echo "Error: Config file is missing required fields"
    echo "Please ensure both GITCODE_USER and TOKEN are set in $CONFIG_FILE"
    exit 1
fi

# Create JSON payload using jq
json_payload=$(jq -n \
    --arg title "$TITLE" \
    --arg body "$TITLE" \
    --arg assignee "$GITCODE_USER" \
    --arg repo "$ISSUE_REPO" \
    '{
        repo: $repo,
        title: $title,
        body: $body,
        assignee: $assignee,
        milestone: 0,
        labels: "bug",
        security_hole: "false",
        template_path: ""
    }')

# Reduced output for issue creation
echo "Feature branch: $BRANCH_NAME"
echo "Target branch: $TARGET_BRANCH"
echo "Repositories: ${REPO_NAMES[*]}"

response=$(curl -s -w "%{http_code}" -L "https://api.gitcode.com/api/v5/repos/${TARGET_ORG}/issues?access_token=$TOKEN" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -d "$json_payload")

# Extract HTTP status code (last 3 characters)
http_code="${response: -3}"
# Extract response body (all but last 3 characters)
response_body="${response:0:${#response}-3}"

if [[ $http_code -ge 200 && $http_code -lt 300 ]]; then
    # Extract html_url and number (issue ID) from response
    html_url=$(echo "$response_body" | jq -r '.html_url')
    ISSUE_ID=$(echo "$response_body" | jq -r '.number')
    
    if [[ -n "$html_url" && "$html_url" != "null" && -n "$ISSUE_ID" && "$ISSUE_ID" != "null" ]]; then
        echo "Issue URL: $html_url"
        
        # Create pull requests for each repository
        echo ""
        echo "Creating pull requests:"
        
        # Track PR creation status and first PR number
        all_prs_successful=true
        first_pr_number=""
        
        for REPO_NAME in "${REPO_NAMES[@]}"; do
            # Determine head value based on whether GITCODE_USER equals TARGET_ORG
            if [[ "$GITCODE_USER" == "$TARGET_ORG" ]]; then
                HEAD="$BRANCH_NAME"
            else
                HEAD="$GITCODE_USER:$BRANCH_NAME"
            fi
            
            # Create PR payload using jq
            pr_payload=$(jq -n \
                --arg title "$TITLE" \
                --arg head "$HEAD" \
                --arg base "$TARGET_BRANCH" \
                --arg body "https://gitcode.com/$TARGET_ORG/$ISSUE_REPO/issues/$ISSUE_ID  $TITLE" \
                --arg fork_path "$GITCODE_USER/$REPO_NAME" \
                '{
                    title: $title,
                    head: $head,
                    base: $base,
                    body: $body,
                    milestone_number: 0,
                    labels: "bug",
                    issue: "",
                    assignees: "",
                    testers: "",
                    prune_source_branch: true,
                    draft: false,
                    squash: false,
                    squash_commit_message: "",
                    fork_path: $fork_path
                }')
            
            # Create pull request
            pr_response=$(curl -s -w "%{http_code}" -L "https://api.gitcode.com/api/v5/repos/$TARGET_ORG/$REPO_NAME/pulls?access_token=$TOKEN" \
              -H 'Content-Type: application/json' \
              -H 'Accept: application/json' \
              -d "$pr_payload")
            
            # Extract HTTP status code
            pr_http_code="${pr_response: -3}"
            pr_response_body="${pr_response:0:${#pr_response}-3}"
            
            if [[ $pr_http_code -ge 200 && $pr_http_code -lt 300 ]]; then
                # Extract PR number and construct URL
                pr_number=$(echo "$pr_response_body" | jq -r '.number')
                
                # Store the first PR number for build triggering
                if [[ -z "$first_pr_number" && -n "$pr_number" && "$pr_number" != "null" ]]; then
                    first_pr_number="$pr_number"
                fi
                
                if [[ -n "$pr_number" && "$pr_number" != "null" ]]; then
                    constructed_url="https://gitcode.com/$TARGET_ORG/$REPO_NAME/pull/$pr_number"
                    echo "  ✓ $REPO_NAME: $constructed_url"
                else
                    echo "  ⚠ $REPO_NAME: PR created but could not extract PR number"
                fi
            else
                # Extract error message or use fallback
                error_message=$(echo "$pr_response_body" | jq -r '.error_message')
                if [[ -n "$error_message" && "$error_message" != "null" ]]; then
                    echo "  ✗ $REPO_NAME: $error_message"
                else
                    echo "  ✗ $REPO_NAME: Failed to open PR: $pr_response_body"
                fi
                all_prs_successful=false
            fi
        done
        
        # If all PRs were created successfully, trigger build on the first PR
        if [[ "$all_prs_successful" == true && -n "$first_pr_number" ]]; then
            echo ""
            echo "All PRs created successfully. Triggering build..."
            
            # Create build comment payload
            build_payload=$(jq -n --arg body "start build" '{body: $body}')
            
            # Trigger build by adding comment to the first PR
            build_response=$(curl -s -w "%{http_code}" -L "https://api.gitcode.com/api/v5/repos/$TARGET_ORG/$ISSUE_REPO/pulls/$first_pr_number/comments?access_token=$TOKEN" \
              -H 'Content-Type: application/json' \
              -H 'Accept: application/json' \
              -d "$build_payload")
            
            # Extract HTTP status code
            build_http_code="${build_response: -3}"
            build_response_body="${build_response:0:${#build_response}-3}"
            
            if [[ $build_http_code -ge 200 && $build_http_code -lt 300 ]]; then
                echo "Build triggered successfully on PR #$first_pr_number"
            else
                # Extract error message or use fallback
                build_error_message=$(echo "$build_response_body" | jq -r '.error_message')
                if [[ -n "$build_error_message" && "$build_error_message" != "null" ]]; then
                    echo "Failed to trigger build: $build_error_message"
                else
                    echo "Failed to trigger build: $build_response_body"
                fi
            fi
        else
            echo ""
            echo "Not all PRs were created successfully. Skipping build trigger."
        fi
        
        # Exit with appropriate code based on PR creation success
        if [[ "$all_prs_successful" == true ]]; then
            exit 0
        else
            exit 1
        fi
    else
        echo "Error: Issue created but could not extract URL or ID from response"
        exit 1
    fi
else
    # Extract error message or use fallback
    error_message=$(echo "$response_body" | jq -r '.error_message')
    if [[ -n "$error_message" && "$error_message" != "null" ]]; then
        echo "Error: Failed to create issue: $error_message"
    else
        echo "Error: Failed to create issue: $response_body"
    fi
    exit 1
fi
